package com.jx.smartbot.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import com.gocom.imoss.common.Exception.GoComException;
import com.gocom.imoss.common.Exception.NotFoundException;
import com.jx.smartbot.VO.GoComMessageResult;
import com.jx.smartbot.VO.Result;
import com.jx.smartbot.VO.message.StatusMessage;
import com.jx.smartbot.entity.VoUserinfor;
import com.jx.smartbot.entity.WpAssistant;
import com.jx.smartbot.entity.WpAssistantAgent;
import com.jx.smartbot.entity.WpAssistantGocom;
//import com.jx.smartbot.entity.WpRemind;
import com.jx.smartbot.repository.VoUserinforRepository;
import com.jx.smartbot.repository.WpAssistantRepository;
import com.jx.smartbot.repository.WpRemindRepository;
import com.jx.smartbot.service.SystemSuperApp;
import com.jx.smartbot.util.JacksonUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
@Api(value = "wp的工具，任务助手和消息",description="wp的工具，任务助手和消息")
@RestController 
public class WpTool extends BaseController {
	private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(WpTool.class);
	//private int pageSize=10;
	@Autowired
	WpAssistantRepository wpAssistantRepository;
	@Autowired
	WpRemindRepository wpRemindRepository;
	@Autowired
	VoUserinforRepository voUserinforRepository;
	@Autowired
	RestTemplate restTemplate;
	@Autowired
	SystemSuperApp systemSuperApp;
	@Resource(name="defaultAppId")
	String defaultAppId;
	@Resource(name="apiurl")
	String gocomeApiUrl;
	
	//获取助手列表 分页
	@ApiOperation(value = "获取助手列表 分页", notes = "可以通过name进行模糊查询")  
	@RequestMapping(value = "/assistants", method = RequestMethod.GET)
	@ResponseStatus(HttpStatus.OK)
	public Page<WpAssistant> assistant(
			@ApiParam(required=false)@RequestParam(value = "name", defaultValue = "") String name,
			@RequestParam(value = "page", defaultValue = "0") Integer page,
			@RequestParam(value = "size", defaultValue = "10") Integer size,
			HttpServletRequest request) {
		 Sort sort = new Sort(Direction.DESC, "id");
		 Pageable pageable = new PageRequest(page, size, sort);
		 Page<WpAssistant> pw=null;
		 if(name.equals("")){
			 pw= wpAssistantRepository.findAll(pageable);
		 }else{
			 pw= wpAssistantRepository.findByNameLike("%"+name+"%",pageable);
		 }
		 if(pw!=null){
			 List<WpAssistant> lw=pw.getContent();
			 for(WpAssistant w:lw){
				 for(WpAssistantAgent wa:w.getWpAssistantAgents()){
					 VoUserinfor vu=voUserinforRepository.findVoUserinforByUserid(wa.getUserId());
					 if(vu==null){
						 wa.setUserName(wa.getUserId());
					 }else{
						 wa.setUserName(vu.getTruename());
					 }
				 } 
			 }
		 }
		 return pw;
	}
	//添加助手
	@ApiOperation(value = "添加助手", notes = "")  
	@RequestMapping(value = "/assistants/add", method = RequestMethod.POST)
	@ResponseStatus(HttpStatus.OK)
	public WpAssistant assistant_add(
			@RequestBody WpAssistant assistant,
			HttpServletRequest request) {
		return wpAssistantRepository.save(assistant);
	}
	//编辑助手
	@ApiOperation(value = "编辑助手", notes = "")  
		@RequestMapping(value = "/assistants/edit", method = RequestMethod.PUT)
		@ResponseStatus(HttpStatus.OK)
		public WpAssistant assistant_edit(
				@RequestBody WpAssistant assistant,
				HttpServletRequest request) {
			return wpAssistantRepository.save(assistant);
		}
	//编辑助手
		@ApiOperation(value = "工具绑定助手", notes = "")  
		@RequestMapping(value = "/assistant/{id}/bing/{superid}", method = RequestMethod.PUT)
		@ResponseStatus(HttpStatus.OK)
		public WpAssistant assistant_bing(
				@PathVariable("id") long id,
				@PathVariable("superid") String superid,
				HttpServletRequest request) {
			WpAssistant assistant=wpAssistantRepository.getWpAssistantById(id);
			if(assistant==null){
				   throw new NotFoundException(500,id+"不在数据库中");
			}
			WpAssistantGocom ag=assistant.getWpAssistantGocom();
			if(assistant.getWpAssistantGocom()==null){
				ag=new WpAssistantGocom();
				assistant.setWpAssistantGocom(ag);
				ag.setWpAssistant(assistant);
			}
			//这里需要调用 gocom管理接口，查询到超级服务号id和appid；目前直接写，以后改
			ag.setSuperid(superid);
			ag.setAssistantName(assistant.getName());
			return wpAssistantRepository.save(assistant);
		}
	//id 查找
	@ApiOperation(value = "查找助手", notes = "通过id查找")  
	@RequestMapping(value = "/assistants/{id}", method = RequestMethod.GET)
	@ResponseStatus(HttpStatus.OK)
	public WpAssistant assistant_id(
			@PathVariable("id") long id,
			HttpServletRequest request) {
		 WpAssistant w =wpAssistantRepository.getWpAssistantById(id);
		 for(WpAssistantAgent wa:w.getWpAssistantAgents()){
			 VoUserinfor vu=voUserinforRepository.findVoUserinforByUserid(wa.getUserId());
			 if(vu==null){
				 wa.setUserName(wa.getUserId());
			 }else{
				 wa.setUserName(vu.getTruename());
			 }
		 } 

		return w;
	}
	//name 查找
	@ApiOperation(value = "查找助手 for name", notes = "通过name查找,不支持模糊")  
	@RequestMapping(value = "/assistants/name/{n}", method = RequestMethod.GET)
	@ResponseStatus(HttpStatus.OK)
	public WpAssistant assistant_name(
			@PathVariable("n") String n,
			HttpServletRequest request) {
		return wpAssistantRepository.getWpAssistantByName(n);
	}
	//助手删除 by id
	@ApiOperation(value = "助手删除 by id", notes = "")  
	@RequestMapping(value = "/assistants/{id}", method = RequestMethod.DELETE)
	@ResponseStatus(HttpStatus.OK)
	public Object assistant_del(
			@PathVariable("id") long id,
			HttpServletRequest request) {
		wpAssistantRepository.delete(id);
		return null;
	}
	/*//助手提醒 添加
	@RequestMapping(value = "/reminds/add", method = RequestMethod.POST)
	@ResponseStatus(HttpStatus.OK)
	public WpRemind remind_add(
			@RequestBody WpRemind wpRemind,
			HttpServletRequest request) {
		return wpRemindRepository.save(wpRemind);
	}
	//助手提醒 状态更改
	@RequestMapping(value = "/reminds/{id}/edit/{status}", method = RequestMethod.PUT)
	@ResponseStatus(HttpStatus.OK)
	public int remind_edit(
			@PathVariable("id") long id,
			@PathVariable("status") int status,
			HttpServletRequest request) {
		return wpRemindRepository.setFixedIdFor(status, id); 
	}
	
	*/
	@ApiOperation(value = "助手发送消息 by id", notes = "给一个助手发消息，可以同时发给多个人，touser 为String tousers 为 []，优先级依次：组，个人，多人")  
	@RequestMapping(value = "/assistants/{id}/sendmessage", method = RequestMethod.POST)
	@ResponseStatus(HttpStatus.OK)
	public GoComMessageResult assistant_send(
			@PathVariable("id") long id,
			//@RequestBody String message,
			@RequestBody StatusMessage message,
			HttpServletRequest request) throws CloneNotSupportedException, UnrecognizedPropertyException {
		if(id==0L){
			return  reminds_send(message,request);
		}
		WpAssistant wpAssistant= wpAssistantRepository.getWpAssistantById(id);
		if(wpAssistant==null){
			 throw new NotFoundException(500,id+"不在数据库中");
		}
		if(wpAssistant.getWpAssistantGocom()==null){
			throw new NotFoundException(501,id+"没有绑定工具");
		}
		String app_str=systemSuperApp.appid_token(wpAssistant.getWpAssistantGocom().getSuperid(), wpAssistant.getWpAssistantGocom().getSecret(), wpAssistant.getWpAssistantGocom().getAppid());
		//app_str=systemSuperApp.appid_token(wpAssistant.getWpAssistantGocom().getSuperid(), wpAssistant.getWpAssistantGocom().getSecret(), wpAssistant.getWpAssistantGocom().getAppid());
		//return this.message_send(app_str,message);
		return this.send_message(app_str,message);
	}
	
	@ApiOperation(value = "默认助手发送消息 by id", notes = "给一个助手发消息，可以同时发给多个人，touser 为String tousers 为 []，优先级依次：组，个人，多人")  
	@RequestMapping(value = "/reminds/send", method = RequestMethod.POST)
	@ResponseStatus(HttpStatus.OK)
	public GoComMessageResult reminds_send(
			@RequestBody StatusMessage message,
			HttpServletRequest request) throws CloneNotSupportedException {
		String app_str=systemSuperApp.appid_token(defaultAppId);
		return this.send_message(app_str,message);
		//return  this.message_send(defaultAppId,message);
	}
	private String sendMessage(String url,String message){
		return restTemplate.postForObject(url,message,String.class);
	}
	private GoComMessageResult sendMessage(String url,StatusMessage message){
		//logger.info("================>{}",url);
		String rt=restTemplate.postForObject(url,message,String.class);
		
		GoComMessageResult re=JacksonUtil.readValue(rt,GoComMessageResult.class);
		return re;
	}
	
	private GoComMessageResult send_message(String appStr,StatusMessage message) throws CloneNotSupportedException{
		String addr="";
		if(message.getTogroup()!=null){
			addr=gocomeApiUrl +"message/groupapp/send/status?"+appStr;
			return sendMessage(addr,message);
		}
		
		
		
		/*if(message.getTouser()==null && message.getTousers()==null ){
			if(message.getTogroup()==null){
				new NotFoundException(502,"必须提供消息发送者");
			}
			
		}*/
		if(message.getTouser()!=null){
			addr=gocomeApiUrl +"message/single/send/status?"+appStr;
			return sendMessage(addr,message);
		}
		if(message.getTousers()!=null && message.getTousers().size()>0){
			addr=gocomeApiUrl +"message/single/send/status?"+appStr;
			//return sendMessage(addr,message);
			List<String> tousers=message.getTousers();
			for(String tuser:tousers){
				StatusMessage newmess=(StatusMessage)message.clone();
				newmess.setTouser(tuser);
				 sendMessage(addr,newmess);
			}
			return new GoComMessageResult();
		}
		
		/*if(touser instanceof List){
			logger.info("====touser instanceof List============>");
			addr=gocomeApiUrl +"message/single/send/status?"+appStr;
			@SuppressWarnings("unchecked")
			List<String> tousers=(List<String>)touser;
			for(String tuser:tousers){
				StatusMessage newmess=(StatusMessage)message.clone();
				logger.info("================>{}",tuser);
				newmess.setTouser(tuser);
				 sendMessage(addr,newmess);
			}
			return new GoComMessageResult();
		}*/
		throw new GoComException("-1","system error");
	}
	private String message_send(String appStr,String message){
		String error_str="{\"errcode\":-1,\"errmsg\":\"system error\"}";
		if(appStr==null){
			return error_str;
		}
		//String appid=systemSuperApp.appid_token(appStr);
		String addr=gocomeApiUrl +"message/single/send/status?"+appStr;
		@SuppressWarnings("unchecked")
		Map<String,Object> map=JacksonUtil.readValue(message, Map.class);
		Object touser=map.get("touser");
		if(touser instanceof  String ){
			return sendMessage(addr,message);//{"errcode":0,"errmsg":"ok","id":744}
		}
		if(touser instanceof  List ){
			@SuppressWarnings("unchecked")
			List<String> tousers=(List<String>)touser;
			for(String tuser:tousers){
				@SuppressWarnings("unchecked")
				Map<String,Object> map_=JacksonUtil.readValue(message, Map.class);
				map_.put("touser", tuser);
				String mss=JacksonUtil.toJSon(map_);
				sendMessage(addr,mss);
			}
			return "{\"errcode\":0,\"errmsg\":\"ok\"}";
		}
		//message/single/send
		// message/mass/send
		//String addr=gocomeApiUrl +"message/single/send/status?"+appid;
		return error_str;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
